package com.learn.demo.array;

/**
 * 删除排序数组中的重复项
 *
 * @author banjiawei
 * @date 2021/06/02
 */
public class RemoveDuplicatesSortedArray {
    public static void main(String[] args) {
        int nums[] = {0,1,1,1,2,2,3,3,3,3,4,4,4,5,6,7,7,7};
        int len = myselfRemove(nums);
        System.out.println(len);
    }

    /**
     * 个人硬写法
     * @author banjiawei
     * @date 2021/6/1
     * @param nums
     * @return int
     */
    public static int myselfRemove(int nums[]){
        if(null != nums && nums.length > 0){
            int one = nums[0];
            int result[] = {nums[0]};
            for (int i = 1; i < nums.length; i++) {
                if (one != nums[i]) {
                    one = nums[i];
                    int temp[] = result;
                    result = new int[temp.length + 1];
                    System.arraycopy(temp, 0, result, 0, temp.length);
                    result[temp.length] = one;
                }
            }
            System.arraycopy(result, 0, nums, 0, result.length);
            return result.length;
        }
        return 0;
    }

    /**
     * 题解双指针法
     * @author banjiawei
     * @date 2021/6/1
     * @param nums
     * @return int
     */
    public static int removeDuplicates(int[] nums) {
        if(null != nums && nums.length > 0){
            int n = nums.length;
            int j = 0;
            for (int i = 0; i < n; i++) {
                if (nums[i] != nums[j]) {
                    nums[++j] = nums[i];
                }
            }
            return j + 1;
        }
        return 0;
    }
}
